#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<ctype.h>
#include<sys/stat.h>
#include<fcntl.h>

#define NoneRedir -1
#define StdinRedir 0
#define StdoutRedir 1
#define AppenRedir 2

char* filename = NULL;
int redir_type = -1;

#define IsSpace(buf, pos) do{while(isspace(buf[pos])) pos++;}while(0)

#define SIZE 1024
#define SP " "

char* argv[SIZE];
char env[SIZE];

int exit_code;

char* HostName()
{
    char* ret = getenv("HOSTNAME");
    if(ret) return ret;
    else return (char*)"None";
}

char* UserName()
{
    char* ret = getenv("USER");
    if(ret) return ret;
    else return (char*)"None";
}

char* CurrentWorkdir()
{
    char* ret = getenv("PWD");
    if(ret) return ret;
    else return (char*)"None";
}

int Interative(char* in)
{
    printf("[%s@%s %s]#", UserName(), HostName(), CurrentWorkdir());
    fgets(in, SIZE, stdin);
    in[strlen(in) - 1] = '\0'; 

    return strlen(in) - 1;
}

void CheckRedir(char* in)
{
    filename = NULL;
    redir_type = -1;

    int pos = strlen(in) - 1;
    while(pos >= 0)
   {
       if(in[pos] == '>')
       {
            if(in[pos - 1] == '>')
            {
                redir_type = 2;
                in[pos - 1] = '\0';
                pos++;
                IsSpace(in, pos);
                filename = in + pos;
                break;
            }
            else 
            {
                redir_type = 1;
                in[pos] = '\0';
                pos++;
                IsSpace(in, pos);
                filename = in + pos;
                break;
            }
       }
       else if(in[pos] == '<')
       {
            redir_type = 0;
            in[pos] = '\0';
            pos++;
            IsSpace(in, pos);
            filename = in + pos;
            break;
       }
       else 
       { 
            pos--;
       }

 }
}

void Split(char* in)
{   
    CheckRedir(in);

    int i = 0;
    argv[i++] = strtok(in, SP);
    while(argv[i++] = strtok(NULL, SP));

    if(strcmp("ls", argv[0]) == 0)
    {
        argv[i-1] = (char*)"--color";
        argv[i] = NULL;
    }
}

int BuiltinCmd()
{
      int ret = 0;
    if(strcmp("cd", argv[0]) == 0)
   {
        ret = 1;
        char* target = argv[1];
        if(!target) target = getenv("HOME");
        chdir(target);
        
        char tmp[SIZE];
        char pwd[SIZE];
        getcwd(tmp, SIZE);

        snprintf(pwd, SIZE, "PWD=%s", tmp);
        
        putenv(pwd);
    }
    else if(strcmp("export", argv[0]) == 0)
    {
        ret = 1;
        if(argv[1])
        {
            strcpy(env, argv[1]);
            putenv(env);
        }
    }
    else if(strcmp("echo", argv[0]) == 0)
    {
        ret = 1;
        if(!argv[1])
            printf("\n");
        else if(argv[1][0] != '$')
            printf("%s\n", argv[1]);
        else 
        {
            if(argv[1][1] == '?')
            {
            
                printf("%d\n", exit_code);
                exit_code = 0;
            }
            else 
                printf("%s\n", getenv(argv[1] + 1));
        }
    }

    return ret; 
}

void Execute()
{
    pid_t id = fork();
    
    if(id == 0)
    {
        int fd = -1;
        if(redir_type == StdinRedir)
        {
            fd = open(filename, O_RDONLY);
            dup2(fd, 0);
        }
        else if(redir_type == StdoutRedir)
        {
            fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            dup2(fd, 1);
        }
        else if(redir_type == AppenRedir)
        {
            fd = open(filename, O_WRONLY|O_CREAT|O_APPEND, 0666);
            dup2(fd, 1);
        }


        execvp(argv[0], argv);
        exit(1);
    }

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)
    {
        exit_code = WEXITSTATUS(status);
    }
}

int main()
{
    char CommandLine[SIZE];
    
    while(1)
    {
        //1.打印提示符+获取用户输入的命令行字符串
         int n =  Interative(CommandLine); 
         if(n == 0) continue;

         //2.分割命令行字符串
         Split(CommandLine);
         
         //3.处理内建命令
         n = BuiltinCmd();
         if(n) continue;

         //4.执行命令(创建子进程，进行替换)
            Execute();
    }

    return 0;
}
